package com.sinoglobal.ningxia.activity.mico;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.widget.VerticalSeekBar;

/**
 * 
 * @title: BaseHVideoPlayActivity.java
 * @package com.sinoglobal.ningxia.activity.mico
 * @description: 视频播放基类
 * @author ty
 * @date 2013-12-16 下午1:25:59
 */
public class BaseHVideoPlayActivity extends Activity implements OnClickListener, OnErrorListener, OnInfoListener, OnCompletionListener {

	public MediaPlayer mediaPlayer;
	protected AudioManager mAudioManager = null;;// 声音管理
	public boolean mediaPlayerState = true;
	protected int currentVolume = 0;// 得到当前媒体音量
	protected SurfaceView surface;
	protected String url = "http://wafmapp.sinosns.cn/ILIMS_Data/ILIMS_Video/mantoumofahe.mp4";// 视频路径
	protected boolean requirePlay = false;// 是否正在播放
	protected int currentPosition = 0, currentPosition2;// 播放当前位置
	// 时间变量
	private int minute;
	private int hour;
	private int second;
	private boolean isOn2Off = false;
	calculationThread mThread;
	protected final int PROGRESS_CHANGED = 0;
	protected final int PROGRESS_CHANGED1 = 6;
	protected final int PAUSE = 1;// 暂停
	protected final int PLAY = 2;// 播放
	protected final int SURFACEISVISIABLE = 3;
	protected final int SEEKING = 4;
	// 重新播放
	protected final int RESTART = 5;
	protected int mDuration;// 总时长
	protected final int STATE_ERROR = 0;
	protected final int STATE_IDLE = 1;
	protected final int STATE_PLAY = 2;// 开始播放
	protected int mCurrentState;// 播放状态，0错误，1准备，2正在播放
	protected int allMinute;// 总分钟
	protected int allHour;// 总小时
	protected int allSecond;// 总秒数

	protected boolean isVisiable = true;// 屏幕上下部分true为显示状态̬
	protected Message message;
	protected long lastTimeonProgressChanged;
	protected static long CLICK_INTERVAL = 800;// 两次滑动的间距时间
	protected boolean isBeginPlayer, isBig;// 视频是否从头播放,是否大屏播放
	protected boolean isPlay = false;// 大屏切小屏时，是否是播放状态̬
	boolean isPlayState = true;// 默认是播放状态
	// 视频宽度和高度
	// int sur_width, sur_height;

	// 用于处理拖动调进度更新、播放时间进度更新、隐藏控制面板消息

	@SuppressLint("HandlerLeak")
	protected Handler mHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PROGRESS_CHANGED:
				calculationTime();
				sendEmptyMessageDelayed(PROGRESS_CHANGED, 100);
				break;
			case SURFACEISVISIABLE:
				if (isVisiable) {
					isVisiable = false;
					includeBotton.setVisibility(View.INVISIBLE);
					includeTop.setVisibility(View.INVISIBLE);
					includeVolume.setVisibility(View.INVISIBLE);
				} else {
					isVisiable = true;
					includeBotton.setVisibility(View.VISIBLE);
					includeTop.setVisibility(View.VISIBLE);
					includeVolume.setVisibility(View.VISIBLE);
				}
				break;
			case SEEKING:
				break;
			// 滑动手势更新时间
			case PROGRESS_CHANGED1:
				Map<String, Object> map;
				map = (Map<String, Object>) msg.obj;
				if (map != null) {
					timeNow.setText(map.get("currentTime").toString());
					seek.setProgress((Integer) map.get("currentPosition"));
				}
				isOn2Off = true;
				break;
			case RESTART:
				currentPosition = mediaPlayer.getCurrentPosition();
				if (mediaPlayer == null || play == null)
					return;
				if (isPlayState) {
					mediaPlayer.pause();
					play.setBackgroundResource(R.drawable.pause);

					seek.setProgress(currentPosition);
				} else {
					mediaPlayer.start();
					play.setBackgroundResource(R.drawable.play);
					seek.setProgress(currentPosition);
				}
				play.performClick();
				break;
			}
		}

	};

	// surface监听处理和初始化
	protected void initSurfaceView() {
		surface.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surface.getHolder().addCallback(new Callback() {// surface初始化的回调
					// SurfaceView发生改变时触发
					public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

					}

					// SurfaceView创建时触发
					public void surfaceCreated(SurfaceHolder holder) {
						// 初始化MediaPlayer

						preMediaplayer();
						// initTimeAndBar();
					}

					// SurfaceView销毁时触发
					public void surfaceDestroyed(SurfaceHolder holder) {

					}
				});

	}

	/* 初始化视频 */
	protected void preMediaplayer() {
		if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.reset();
		}
		try {
			// 设置声音类型
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 设置用来显示视频的对象，SurfView
			mediaPlayer.setDisplay(surface.getHolder());
			// 是否循环播放
			mediaPlayer.setLooping(false);
			// 设置数据源url为视频播放地址
			mediaPlayer.setDataSource(url);
			// 异步加载数据
			mediaPlayer.prepareAsync();
			// 监听接口，监听播放器状态信息
			mediaPlayer.setOnInfoListener(this);
			// 监听接口，监听播放器错误信息内容
			mediaPlayer.setOnErrorListener(this);
			// 监听接口，监听播放完成
			mediaPlayer.setOnCompletionListener(this);
			// 视频准备接口，视频播放前调用此方法
			mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// 初始化时间进度条
					initTimeAndBar();
					mCurrentState = PLAY;
					RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					lp.addRule(RelativeLayout.CENTER_IN_PARENT);
					surface.setLayoutParams(lp);
					mp.start();
					loading.setVisibility(View.INVISIBLE);
				}
			});
		} catch (Exception e) {
			ItktLog.e("preMediaplayer执行失败" + e);
			loading.setVisibility(View.INVISIBLE);
		}
	}

	protected View includeBotton, includeTop, includeVolume;// 视频底部、上部、声音
	protected Button play;// 视频播放按钮
	protected Button open;
	protected SeekBar seek;// 视频播放进度条
	protected VerticalSeekBar volumeSeek;// 声音进度条
	protected TextView timeNow, timeAll;// 视频播放时间
	protected RelativeLayout big, playRe;// 全屏父布局,播放父布局
	RelativeLayout loading;// loading部分
	protected ImageButton back;// back键
	protected ImageButton share;// 分享键
	// 当前提示信息，当使用滑动来改变声音、播放进度时提示用户
	protected TextView mTostinfo;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.play:// 播放/暂停
			/*
			 * if (SinoAppliacation.mediaPlayer == null) {
			 * SinoAppliacation.mediaPlayer = new MediaPlayer(); }
			 */
			if (mediaPlayer.isPlaying()) {
				ItktLog.i("State is Playing");
				mediaPlayer.pause();
				play.setBackgroundResource(R.drawable.play);
			} else {

				ItktLog.i("State is Pause");
				mediaPlayer.start();
				play.setBackgroundResource(R.drawable.pause);
			}
			break;
		case R.id.surface:// 点击屏幕隐藏
			message = new Message();
			message.what = SURFACEISVISIABLE;
			mHandler.sendMessageDelayed(message, 300);
			break;
		case R.id.open:// 全屏显示
			// mHandler.removeMessages(PROGRESS_CHANGED);
			// Intent intent = new Intent();
			// if (SinoAppliacation.mediaPlayer.isPlaying()) {
			// intent.putExtra("mediaplay", "play");
			// SinoAppliacation.mediaPlayer.pause();
			// } else {
			// intent.putExtra("mediaplay", "pause");
			// }
			// intent.setClass(BaseHVideoPlayActivity.this,
			// VideoHActivity.class);
			// BaseHVideoPlayActivity.this.startActivityForResult(intent, 0);
			// clear();
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

			} else {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}

			break;
		// 返回
		case R.id.back:
			finish();
			break;
		// 分享功能
		case R.id.share_sns:
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case -1:
			if (data != null) {
				String current = data.getStringExtra("mediaplay");
				if ("true".equals(data.getStringExtra("play"))) {
					isPlay = true;
					play.setBackgroundResource(R.drawable.pause);
				} else {
					isPlay = false;
					play.setBackgroundResource(R.drawable.play);
				}
				currentPosition2 = Integer.parseInt(current);
				ItktLog.i(currentPosition);

			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 得到音乐、视频文件播放时时间的总长度
	 */
	public int getDuration() {
		if (isInPlaybackState()) {
			if (mDuration > 0) {
				return mDuration;
			}
			mDuration = mediaPlayer.getDuration();
			return mDuration;
		}
		mDuration = -1;
		return mDuration;
	}

	// 是否可以播放情况一切可好
	protected boolean isInPlaybackState() {
		return (mediaPlayer != null);
	}

	// 设置音量大小
	protected void updateVolume(int volume) {
		if (mAudioManager != null) {
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
			currentVolume = volume;
		}
	}

	/**
	 * @author ty
	 * @createdate 2013-12-16 下午4:36:21
	 * @Description: (用一句话描述该方法做什么)
	 * @param isBeginPlayer是否从头播放
	 * @param isBig是否是大屏播放
	 * @param currentPossiton播放起始位置
	 */

	protected void findVideoId(boolean isBeginPlayer, boolean isBig) {

		this.isBeginPlayer = isBeginPlayer;
		this.isBig = isBig;
		mTostinfo = (TextView) findViewById(R.id.Toast_Volume);
		mTostinfo.setVisibility(View.GONE);
		surface = (SurfaceView) findViewById(R.id.surface);
		includeBotton = findViewById(R.id.include_botton);
		includeTop = findViewById(R.id.include_top);
		play = (Button) includeBotton.findViewById(R.id.play);
		seek = (SeekBar) includeBotton.findViewById(R.id.seekBar);
		includeVolume = findViewById(R.id.include_volume);
		volumeSeek = (VerticalSeekBar) includeVolume.findViewById(R.id.Volume_SeekBar);
		timeNow = (TextView) includeBotton.findViewById(R.id.time1);
		timeAll = (TextView) includeBotton.findViewById(R.id.time2);
		open = (Button) includeBotton.findViewById(R.id.open);
		loading = (RelativeLayout) findViewById(R.id.loading);
		play.setOnClickListener(this);
		open.setOnClickListener(this);
		surface.setOnClickListener(this);
		/*
		 * surface.setOnTouchListener(new OnTouchListener() {
		 * 
		 * @Override public boolean onTouch(View v, MotionEvent event) {
		 * //Auto-generated method stub mGestureDetector.onTouchEvent(event);
		 * return true; } });
		 */
		back = (ImageButton) includeTop.findViewById(R.id.back);
		back.setOnClickListener(this);
		share = (ImageButton) includeTop.findViewById(R.id.share_sns);
		share.setOnClickListener(this);
		// 当播放器不为空时，onCreate（）时重新计算
		if (mediaPlayer != null && mCurrentState == PLAY) {

			// initTimeAndBar();
			currentPosition = mediaPlayer.getCurrentPosition();
			seek.setProgress(currentPosition);
			calculationTime();
			if (mediaPlayer.isPlaying())
				includeBotton.setVisibility(View.INVISIBLE);
		}

		seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				if (mCurrentState == STATE_PLAY) {
					mediaPlayer.seekTo(seek.getProgress());

				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// mHandler.removeMessages(PROGRESS_CHANGED);

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				currentPosition = progress;
				mHandler.sendEmptyMessageDelayed(PROGRESS_CHANGED, 100);
			}
		});
		// 音量控制
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);// 音频管理服务
		currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);// 得到视频当前音量
		volumeSeek.setMax(30);
		volumeSeek.setProgress(currentVolume);
		updateVolume(currentVolume);
		volumeSeek.setOnSeekBarChangeListener(new VerticalSeekBar.OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				updateVolume(progress);// 设置音量显示
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}
		});
	}

	class calculationThread extends Thread {

		public void run() {
			while (isOn2Off) {
				// isOn2Off=false;
				calculationTime1();
				try {
					sleep(800);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void calculationTime1() {
		String currentTime;
		if (!isInPlaybackState())
			mediaPlayer = new MediaPlayer();
		int currentposition;
		try {
			currentposition = mediaPlayer.getCurrentPosition();
		} catch (Exception e) {
			currentposition = 0;
		}

		currentPosition = currentposition;
		currentPosition /= 1000;
		minute = currentPosition / 60;
		hour = minute / 60;
		second = currentPosition % 60;
		minute %= 60;
		if (hour > 0) {
			currentTime = String.format("%02d:%02d:%02d", hour, minute, second);
		} else {
			currentTime = String.format("%02d:%02d", minute, second);
		}
		Message msg = new Message();
		msg.what = PROGRESS_CHANGED1;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentTime", currentTime);
		map.put("currentPosition", currentposition);
		msg.obj = map;
		mHandler.sendMessage(msg);

	}

	// 计算显示时间
	protected void calculationTime() {
		if (mThread == null) {
			isOn2Off = true;
			mThread = new calculationThread();
			mThread.start();
		}

	}

	// 初始化时间、进度条
	protected void initTimeAndBar() {
		int i = getDuration();
		seek.setMax(i);
		i /= 1000;
		allMinute = i / 60;
		allHour = allMinute / 60;
		allSecond = i % 60;
		allMinute %= 60;
		if (allHour > 0) {
			timeNow.setText((String.format("%02d:%02d:%02d", 0, 0, 0)));
			timeAll.setText("/" + String.format("%02d:%02d:%02d", allHour, allMinute, allSecond));
		} else {
			timeNow.setText(String.format("%02d:%02d", 0, 0));
			timeAll.setText("/" + String.format("%02d:%02d", allMinute, allSecond));
		}
		mCurrentState = STATE_PLAY;
		// loading.setVisibility(View.INVISIBLE);

	}

	protected void clear() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	// 监听声音控制键
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 获取手机当前音量值
		if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			currentVolume -= 1;
			if (currentVolume < 0)
				currentVolume = 0;
			updateVolume(currentVolume);
			volumeSeek.setProgress(currentVolume);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			currentVolume += 1;
			if (currentVolume > 100)
				currentVolume = 100;
			updateVolume(currentVolume);
			volumeSeek.setProgress(currentVolume);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			clear();
			finish();

		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if (mediaPlayer != null) {
			message = new Message();
			message.what = RESTART;
			mHandler.sendMessage(message);
		}
	}

	@Override
	protected void onDestroy() {
		Log.e("media", "onDestroy");
		// 释放mediaplay
		if (mediaPlayer != null) {
			try {
				isOn2Off = false;

				mediaPlayer.stop();
				mediaPlayer.release();
			} catch (Exception e) {
				e.printStackTrace();

			}

		}
		super.onDestroy();

	}

	@Override
	protected void onPause() {
		ItktLog.i("onPause1");
		if (mediaPlayer != null) {
			if (mCurrentState == STATE_PLAY) {
				if (mediaPlayer.isPlaying())
					isPlayState = true;
			} else
				isPlayState = false;
			mediaPlayer.pause();

			// play.setBackgroundResource(R.drawable.pause);
		}
		super.onPause();

	}

	private String getActionName(int action) {
		String name = "";
		switch (action) {
		case MotionEvent.ACTION_DOWN: {
			name = "ACTION_DOWN";
			break;
		}
		case MotionEvent.ACTION_MOVE: {
			name = "ACTION_MOVE";
			break;
		}
		case MotionEvent.ACTION_UP: {
			name = "ACTION_UP";
			break;
		}
		default:
			break;
		}
		return name;
	}

	class MyOnGestureListener extends SimpleOnGestureListener {
		// Touch了不移动，一直Touch down时触发
		@Override
		public void onLongPress(MotionEvent e) {
			ItktLog.i("onLongPress-----" + getActionName(e.getAction()));
		}

		// Touch了滑动时触发
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
			int Scr_Width, Scr_height;
			// 捕捉手势滑动
			Scr_Width = Math.abs(Math.round(e2.getX() - e1.getX()));
			Scr_height = Math.abs(Math.round(e2.getY() - e1.getY()));
			String timeNowStr = "当前时间:";
			String voiceNowStr = "当前音量:";
			// 如果是横向滑动距离大于纵向滑动距离,调整播放时间进度条
			if (Scr_Width > Scr_height) {
				try {
					mTostinfo.setVisibility(View.VISIBLE);
					currentPosition = mediaPlayer.getCurrentPosition();
					if (e2.getX() > e1.getX()) {
						if (mediaPlayer.getCurrentPosition() < mDuration)
							currentPosition += 1000;
					} else {
						if (currentPosition > 1000)
							currentPosition -= 1000;
					}

					mTostinfo.setText(timeNowStr + timeNow.getText().toString());
					mediaPlayer.seekTo(currentPosition);
					seek.setProgress(mediaPlayer.getCurrentPosition());
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {// 调整音量大小
				// 竖屏时关闭滑动声音的监听
				if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
					// 滑动距离与声音增加量的比例适当调大一些，比较好。
					mTostinfo.setVisibility(View.VISIBLE);
					if (e1.getY() > e2.getY()) {
						if (currentVolume < 100)
							currentVolume++;
					} else {
						if (currentVolume > 0)
							currentVolume--;
					}
					mTostinfo.setText(voiceNowStr + (currentVolume));
					updateVolume(currentVolume);
					volumeSeek.setProgress(currentVolume);
				}
			}
			return false;
		}

		// Touch了滑动一点距离后，up时触发
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			mTostinfo.setVisibility(View.GONE);

			return true;
		}

		@Override
		public void onShowPress(MotionEvent e) {

		}

		@Override
		public boolean onDown(MotionEvent e) {
			mTostinfo.setVisibility(View.GONE);
			return false;
		}

		// 双击的第二下Touch down时触发
		@Override
		public boolean onDoubleTap(MotionEvent e) {
			ItktLog.i(getActionName(e.getAction()));
			return false;
		}

		// 双击的第二下Touch down和up都会触发，可用e.getAction()区分
		@Override
		public boolean onDoubleTapEvent(MotionEvent e) {
			return false;
		}

		/*
		 * 两个函数都是在Touch Down后又没有滑动(onScroll)，又没有长按(onLongPress)，然后Touch Up时触发
		 * 点击一下非常快的(不滑动)Touch Up: onDown->onSingleTapUp->onSingleTapConfirmed
		 * 点击一下稍微慢点的(不滑动)Touch Up:
		 * onDown->onShowPress->onSingleTapUp->onSingleTapConfirmed
		 */
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			return false;
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			message = new Message();
			message.what = SURFACEISVISIABLE;
			mHandler.sendMessageDelayed(message, 300);
			return false;
		}
	}

	// 监听接口，监听播放器状态信息
	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		switch (what) {
		}
		return true;
	}

	// MediaPlayer错误信息监听
	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		// SinoAppliacation.mediaPlayer.reset();
		mCurrentState = STATE_ERROR;
		switch (what) {
		case 1:
			break;
		case 200:
			mediaPlayer.reset();
			mCurrentState = STATE_PLAY;
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * @author qiwx
	 * @createdate 2014-8-6 15:27:24
	 * @Description:mediaplayer播放完成监听
	 * @type
	 * @throws Exception
	 * @parameters
	 */
	@Override
	public void onCompletion(MediaPlayer mp) {
		if (mp != null)
			play.setBackgroundResource(R.drawable.play);

	}

}
